//
//  UserAccount.swift
//  WeiBo
//
//  Created by 刘星 on 16/6/17.
//  Copyright © 2016年 LiuXing. All rights reserved.
//

import UIKit

class UserAccount: NSObject, NSCoding {
    var access_token: String?
    var expires_in: NSNumber?
    var uid: String?
    
    init(dict: [String: AnyObject]) {
        access_token = dict["access_token"] as? String
        expires_in = dict["expires_in"] as? NSNumber
        uid = dict["uid"] as? String
    }
    // 打印一个对象
    override var description: String {
        let properties = ["access_token", "expires_in", "uid"]
        let dict = self.dictionaryWithValuesForKeys(properties)
        return "\(dict)"
    }
    class func userLgoin() -> Bool {
        return UserAccount.loadAccount() != nil
    }
    func saveAccount() {
        let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!
        let filePath = (path as NSString).stringByAppendingPathComponent("account.plist")
//        print("filePath \(filePath)")
        NSKeyedArchiver.archiveRootObject(self, toFile: filePath)
    }
    class func loadAccount() -> UserAccount? {
        let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!
        let filePath = (path as NSString).stringByAppendingPathComponent("account.plist")
//        print("filePath \(filePath)")
        
        let account =  NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? UserAccount
        return account
    }
    // MARK: - NSCoding
    // 将对象写入到文件中
    func encodeWithCoder(aCoder: NSCoder)
    {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
    }
    // 从文件中读取对象
    required init?(coder aDecoder: NSCoder)
    {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeObjectForKey("expires_in") as? NSNumber
        uid = aDecoder.decodeObjectForKey("uid") as? String
    }
}
